<?php

namespace App\Extensions\Grid\Displayers;

use Encore\Admin\Admin;
use Encore\Admin\Grid\Displayers\AbstractDisplayer;

class ModalLink extends AbstractDisplayer
{

    /**
     * @param $callback
     * @return mixed|string
     */
    public function display($callback = null)
    {
        if (func_num_args() == 2) {
            list($title, $callback) = func_get_args();
        } elseif (func_num_args() == 1) {
            $title = '';
        }
        if ($callback instanceof \Closure) {
            $url = call_user_func_array($callback->bindTo($this->row), [$this->row]);
        } else {
            $url = $callback;
        }
        return Admin::component('admin.components.column-modal-link', [
            'url'   => $this->getLoadUrl($url),
            'title' => $title,
            'html'  => '',
            'key'   => $this->getKey(),
            'value' => $this->value,
            'name'  => $this->getKey() . '-' . str_replace('.', '_', $this->getColumn()->getName()),
        ]);
    }

    protected function getLoadUrl($url): string
    {
        return url_add_query($url, [
            'token'   => method_exists($this->row, 'token') ? $this->row->token() : '',
            '_modal_' => 1
        ]);
    }

}
